package moo.stargalaxy_bungee.listener;

import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import moo.stargalaxy_bungee.GalaxyBunGee;
import moo.stargalaxy_bungee.api.GalaxyAPI;
import moo.stargalaxy_bungee.api.GalaxyBungeeAPI;
import moo.stargalaxy_bungee.config.Config;
import moo.stargalaxy_bungee.data.StarGalaxyData;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.event.ServerDisconnectEvent;
import net.md_5.bungee.api.event.ServerKickEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;

import java.net.InetSocketAddress;

public class StarBungeeEvent implements Listener {

    // 子服崩服后直接跨服选定的服务器，避免游戏退出
    @EventHandler
    public void quit(ServerKickEvent event){
        if(Config.getConfiguration().getBoolean("BunGee_Set.Enable_KickGoLobby")){
            if(Config.getConfiguration().getStringList("BunGee_Set.Ignore_KickGoLobby").contains(event.getKickedFrom().getName())){
                return;
            }
            if(GalaxyBungeeAPI.addTpCoolDown(event.getPlayer())){
                event.setCancelled(true);
                event.setCancelServer(event.getKickedFrom());
                event.getPlayer().connect(GalaxyBunGee.getPlugin().getProxy().getServerInfo(Config.getConfiguration().getString("BunGee_Set.Server_Lobby")));
            }
        }
    }

    // 处理来自子服插件隧道的消息数据
    @EventHandler
    public void on(PluginMessageEvent event) {
        if (!event.getTag().equalsIgnoreCase( "stargalaxy:message" ) ) {
            return;
        }
        ByteArrayDataInput in = ByteStreams.newDataInput( event.getData() );
        String subChannel = in.readUTF();
        if (subChannel.equalsIgnoreCase( "OtherSubchannel" ) ) {
            // the receiver is a ProxiedPlayer when a server talks to the proxy
            if (event.getReceiver() instanceof ProxiedPlayer) {
                ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
                if(!GalaxyBungeeAPI.addTpCoolDown(player)){
                    return;
                }
                StarGalaxyData.getCoolDownMap().put(player.getUniqueId(), true);
                String s = in.readUTF();
                GalaxyBunGee.getPlugin().getLogger().info("§7来自群星服务器 §a" + s + " §7的数据请求");
                if(s.equals("hub")){
                    ServerInfo serverInfo = GalaxyBunGee.getPlugin().getProxy().getServers().get(Config.getConfiguration().getString("BunGee_Set.Server_Lobby"));
                    player.connect(serverInfo);
                    return;
                }
                if(GalaxyBunGee.getPlugin().getProxy().getConfig().getServers().get(s)  == null){
                    String[] ip = in.readUTF().split(":");
                    try {
                        InetSocketAddress address = new InetSocketAddress(ip[0], Integer.parseInt(ip[1]));
                        ServerInfo serverInfo = GalaxyBunGee.getPlugin().getProxy().constructServerInfo(s, address, "From Plugin StarGalaxy-Bungee", false);
                        GalaxyBunGee.getPlugin().getProxy().getConfig().getServers().put(s, serverInfo);
                        GalaxyBunGee.getPlugin().getProxy().getConfigurationAdapter().getServers().put(s, serverInfo);
                        //GalaxyBunGee.getPlugin().getProxy().getConfigurationAdapter()
                        StarGalaxyData.getServerInfoMap().put(s, serverInfo);
                        player.connect(serverInfo);
                        GalaxyBunGee.getPlugin().getLogger().info("§7子服务器 §a" + s + " §7添加完成");
                    } catch (Exception e){
                        GalaxyBunGee.getPlugin().getLogger().info("§c在热添加服务器时发生异常");
                        GalaxyBunGee.getPlugin().getLogger().info("§a玩家 §7" + player.getDisplayName() + "§a 发送的 §7" + s + "§a 游戏地址 §7" + ip[0] + ":" + ip[1]);
                    }
                }
                // do things
                player.connect(GalaxyBunGee.getPlugin().getProxy().getServerInfo(s));
                return;
            }
        }
        // 由子服发送的命令信息 其中可能包含空格数据
        if(subChannel.equalsIgnoreCase("zxcommand")){
            String s = in.readUTF();
            GalaxyBunGee.getPlugin().getProxy().getPluginManager().dispatchCommand(GalaxyBunGee.getPlugin().getProxy().getConsole(), s);
        }
    }
}
